#pragma once

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cerrno>

#define FIFO_FILE "FIFO"
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

class NamedFifo
{
public:
    // 构造函数
    NamedFifo(const std::string &path, const std::string &name) : _path(path), _name(name)
    {
        // 新建管道文件
        umask(0);

        _fifoname = _path + "/" + _name; // 管道全名路径+文件名
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n == -1)
        {
            // std::cerr << "mkfifo failed" << std::endl;
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "FIFO created successfully" << std::endl;
        }
        std::cout << std::endl;
    }

    // 析构函数
    ~NamedFifo()
    {
        // 删除管道文件
        int n = unlink(_fifoname.c_str());
        if (n == -1)
        {
            // std::cerr << "unlink failed" << std::endl;
            ERR_EXIT("unlink");
        }
        else
        {
            //
            std::cout << "FIFO deleted successfully" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
public:
    // 构造函数
    FileOper(const std::string &path, const std::string &name) : _path(path), _name(name)
    {
        _fifoname = _path + "/" + _name; // 管道全名路径+文件名
    }

    void OpenForRead()
    {
        // 打开管道文件
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd == -1)
        {
            // std::cout << "open failed" << std::endl;
            ERR_EXIT("open");
        }
        std::cout << "open successfully" << std::endl;
    }

    void OpenForWrite()
    {
        // 以只写方式打开管道文件
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            // std::cerr << "client open failed" << std::endl;
            ERR_EXIT("client open");
        }
        std::cout << "client open success" << std::endl;
    }

    //等待客户端发送消息
    bool Wait()
    {
        char c;
        int n = read(_fd, &c, sizeof(c));
        if(n > 0 )//有数据可读
        {
            return true;
        }
        else//无数据可读
        {
            return false;
        }
        
    }

    // 唤醒服务端
    void Wakeup()
    {
        char c;
        write(_fd, &c, sizeof(c));
    }

    void Close()
    {
        close(_fd);
    }

    // 析构函数
    ~FileOper()
    {
    }

private:
    std::string _path;
    std::string _name;

    std::string _fifoname;
    int _fd;
};
